﻿
using Com.FirstSolver.Splash;
using SocketLib;
using System;
using System.Net;

namespace SocketLib
{
    public class UDPserver : IDgramPacketHandler
    {
        /// <summary>
        /// 设备通信字符集代码页为简体中文
        /// </summary>           
        private const int DeviceCodePage = 936;

        /// <summary>
        /// 服务器是否已运行
        /// </summary>
        private bool IsServerRunning = false;

        /// <summary>
        /// 侦听服务器
        /// </summary>
        private UdpClientPlus UdpServer = null;


        


        public bool Start(string Ips = "*", int port = 9924)
        {
            if (!IsServerRunning)
            {
                try
                {
                    UdpServer = new UdpClientPlus(port);

                    UdpServer.CodePage = DeviceCodePage;    // 通信字符集为简体中文
                    UdpServer.DgramPacketHandler = this;    // 设置心跳包处理程序
                    UdpServer.StartListenThread();
                    FileOpetation.SaveRecord(string.Format(@"当前记录时间：{0},UDP 状况：{1}", DateTime.Now, "UDP 开启"));
                    IsServerRunning = true;
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    FileOpetation.SaveRecord(string.Format(@"当前记录时间：{0},UDP 状况：{1}", DateTime.Now, ex.Message));
                    IsServerRunning = false;
                }



                // buttonStart.Text = "停止侦听";
            }
            return IsServerRunning;
        }

        public void close()
        {
            if (UdpServer != null)
            {
                UdpServer.Close();
                UdpServer = null;


            }

            IsServerRunning = false;
            //buttonStart.Text = "开启侦听";
        }



        void IDgramPacketHandler.OnDgramPacketReceived(IPEndPoint remoteEP, byte[] content)
        {
            throw new NotImplementedException();
        }

        void IDgramPacketHandler.OnDgramPacketReceived(IPEndPoint remoteEP, string content)
        {


            if (content.StartsWith("DevStatus"))
            {
                // 心跳检查 

                String sn = RegexHelper.getAttr(content, "sn");

                if (dao.SetOnline(sn) > 0)
                {
                    //int n= Convert.ToInt32(MySqlHelper.GetSingle(String.Format("select count(1) from lxb_command where status=0 and  sn='{0}'", sn)));
                    // if (MySqlHelper.Exists("select  Id from lxb_device where isok=1 and sn='" + sn + "'"))
                    {
                        //FileOpetation.SaveRecord(string.Format(@"当前记录时间：{0},UDP 状况：{1}", DateTime.Now, "有未执行记录"));
                        UdpServer.Send("PostRequest()", remoteEP, DeviceCodePage);
                    }
                }


            }



        }

    }
}
